import {
  ChangeDetectionStrategy,
  Component,
  ViewChild,
  HostBinding,
  EventEmitter,
  Output,
} from '@angular/core';
import { CdkTree } from '@angular/cdk/tree';
import { TreeNodeOutletDirective } from './tree-node/tree-node-outlet.directive';
import { TreeSelectControl } from './tree-select/tree-select.control';

@Component({
  selector: 'fui-tree',
  template: '<ng-container fuiTreeNodeOutlet></ng-container>',
  changeDetection: ChangeDetectionStrategy.Default,
  providers: [{provide: CdkTree, useExisting: TreeComponent}],
})
export class TreeComponent<T> extends CdkTree<T> {
  @HostBinding('class.fui-tree') hostClass = true;

  @ViewChild(TreeNodeOutletDirective, {static: true}) _nodeOutlet: TreeNodeOutletDirective;

  /** Emit selection change. */
  @Output() selectChange = new EventEmitter<T[]>();

  selectControl: TreeSelectControl<T>;

  select() {
    this.selectControl = this.selectControl || new TreeSelectControl(this);
    return this.selectControl;
  }

  onSelected() {
    if (this.selectChange.observers.length > 0) {
      const selectedData = this.select().getSelectedData();
      this.selectChange.emit(selectedData);
    }
  }
}
